package com.mxf.example.security;

import com.mxf.example.exception.ErrorBody;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        // 将filter中的异常捕获，发送到error controller，交给全局异常处理器处理（springboot全局异常处理不能直接拦截filter中的异常，需要转发处理）
        httpServletRequest.setAttribute("filter.error", e);
        //将异常分发到/error/exthrow控制器
        httpServletRequest.getRequestDispatcher("/error/exthrow").forward(httpServletRequest, httpServletResponse);
        return;
    }
}
